import React from 'react'
import { Link } from 'react-router-dom'
import routes from './routes'

export default function BetterLink({ to, ...restProps }) {

    if (to.name && typeof to !== 'string') {
        to.pathname = getPathName(to.name, '/', routes)
        if(!to.pathname){
            throw new Error(`can not find path by name ${to.name}`)
        }
    }

    return (
        <Link
            {...restProps}
            to={to}
        />
    )
}

/**
 * 根据name，查找对应的path，没有考虑params的情况
 * 如果有params，需要手动拼接
 * @param {string} name 路由名称
 * @param {string} baseUrl 基础url
 * @param {array} routes 路由数组
 */
function getPathName(name, baseUrl, routes) {
    for (const route of routes) {
        const newPath = `${baseUrl}${route.path}`.replace(/\/+/g, '/') // 去除多余的'/'
        if (route.name === name) {
            return newPath
        }
        if (route.children) {
            const path = getPathName(name, newPath, route.children)
            if (path) {
                return path
            }
        }
    }
}